from ctypes import *
import sys
dllpath_win="lib/hluart.dll"
dllpath_linux="lib/libhluart.so"
dllpath_mac="lib/libhluart.dylib"
class Element_Struct(Structure):
    _fields_=[
        ("size",c_uint8),
        ("type",c_uint8),
        ("data",c_uint32)
    ]
data_type_dic={
    1:c_uint8,
    2:c_uint16,
    3:c_uint32,
    4:c_float,
    5:c_int16,
    6:c_int32
}
class HLUART_DLL:
    __dll:CDLL
    type_data_dict:dict
    def __init__(self) -> None:
        com_type=sys.platform
        path=""
        if(com_type=="linux"):
            path=dllpath_linux
        elif(com_type=="win32" or com_type=="cygwin"):
            path=dllpath_win
        elif(com_type=="darwin"):
            path=dllpath_mac
        self.__dll = cdll.LoadLibrary(path)
        self.type_data_dict=dict()
        for k in data_type_dic.keys():
            v=data_type_dic[k]
            self.type_data_dict[v]=k
    def write_buffer(self,buffer:Array[c_uint8],length:int,elements:Array[Element_Struct]):
        '''
        写buffer
        '''
        self.__dll.write_buffer(byref(buffer),length,byref(elements))
    def read_buffer(self,buffer:Array[c_uint8],length:int,elements:Array[Element_Struct]):
        '''
        读取buffer,补充元素组的data(不包含校验，buffer应在外部校验完成才可调用！！！)
        '''
        self.__dll.read_buffer(byref(buffer),length,byref(elements))
    def data(self,val)->c_uint32:
        '''
        转data
        '''
        return self.__dll.data(byref(val),self.type_data_dict[type(val)])
    def val(self,data:c_uint32,data_type:type):
        '''
        转val
        '''
        res=data_type()
        self.__dll.val(byref(res),self.type_data_dict[data_type],data)
        return res
    def type_get_size(self,v_type:int)->int:
        return self.__dll.type_get_size(v_type)
    def get_elements_length(self,buffer:Array[c_uint8])->int:
        return self.__dll.get_elements_length(byref(buffer),len(buffer))
# hluart=HLUART_DLL()
 

# size=hluart.elements_size()
# elements=(Element_Struct*size)()
# buffer_size=hluart.elements_init(elements)
# hluart.data(c_float(3.1))
# elements[0].data=hluart.data(c_float(3.1))
# elements[1].data=hluart.data(c_int16(-3))
# elements[2].data=hluart.data(c_int32(10))
# elements[3].data=hluart.data(c_uint8(63))
# buffer=(c_uint8*buffer_size)()
# print(hluart.val(hluart.data(c_float(3.1)),c_float))
# hluart.write_buffer(buffer,size,elements)
# print(buffer_size)
# for i in range(size):
#     e:Element_Struct=elements[i]
#     print("{}".format(hex(e.data)))
# for b in buffer:
#     print(hex(b),end=" ")

